package com.raycloud.java.dada.util;

import com.alibaba.fastjson.JSON;
import com.raycloud.java.dada.result.CallbackResult;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;

/**
 * Created by:  intelliJ IDEA
 *
 * @Author albert
 * @Description:达达回调服务测试
 * @Date:2017/7/13 下午5:46
 * @package:com.raycloud.java.dada.util
 * @Modified By:
 */
public class CallBackServer implements HttpHandler {
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
        //是否post请求
        if ("POST".equals(httpExchange.getRequestMethod())){
            InputStream inputStream = httpExchange.getRequestBody();
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            StringBuilder body = new StringBuilder();
            while ((line=in.readLine()) != null){
                body.append(line);
            }
            CallbackResult callbackResult = JSON.parseObject(body.toString(),CallbackResult.class);
            response(httpExchange,"ok");
        }else{
             response(httpExchange,"ok");
        }
    }
    private  void response(HttpExchange t, String responseMsg) {
        try {
            t.sendResponseHeaders(HttpURLConnection.HTTP_OK, responseMsg.getBytes().length);
            OutputStream os = t.getResponseBody();
            os.write(responseMsg.getBytes("UTF-8"));
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(8899);
     try {
         HttpServer server = HttpServer.create(inetSocketAddress,0);
         if (server!=null){
             server.createContext("/test",new CallBackServer());
             server.setExecutor(null);
             server.start();
         }
     }catch (Exception e){
         e.printStackTrace();
     }


    }
}
